<?php
use Workerman\Worker;
use Workerman\Lib\Timer;
use Workerman\Lib\Db;

require_once './Autoloader.php';

$config = require_once(__DIR__ . '/Config.php');

// 初始化一个worker容器，监听1234端口
$worker = new Worker('websocket://0.0.0.0:2346');

/*
 * 注意这里进程数必须设置为1，否则会报端口占用错误
 * (php 7可以设置进程数大于1，前提是$inner_text_worker->reusePort=true)
 */

$worker->count = 1;
// worker进程启动后创建一个text Worker以便打开一个内部通讯端口
$worker->onWorkerStart = function($worker)
{
    // 开启一个内部端口，方便内部系统推送数据，Text协议格式 文本+换行符
    $inner_text_worker = new Worker('text://0.0.0.0:5678');
    
    // 设置端口复用，可以创建监听相同端口的Worker（需要PHP>=7.0）
    //$inner_worker->reusePort = true;
    $inner_text_worker->onMessage = function($connection, $buffer)
    {
        global $config,$worker;
        $data = json_decode($buffer, true);
        $roomId = isset($data['roomId']) ? $data['roomId'] : 0;
        $invite_uid = isset($data['invite_uid']) ? $data['invite_uid'] : 0;

        $state = isset($data['state']) ? $data['state'] : 0;
        $channel = isset($data['channel']) ? $data['channel'] : 'hrd';
  
        $ret = '';
        switch($channel){
            case 'ng':
                $ret = sendNgUser($roomId, $buffer);
                break;
                
            case 'hrd':
                $ret = sendHrdUser($roomId, $buffer, $state);
                break;
                
            case 'pw':
                $ret = sendQwUser($roomId, $buffer, $state);
                break;

            case 'monoly':
                $ret = sendMonolyUser($roomId,$invite_uid);
                break;
        }
        
        // 返回推送结果
        $connection->send($ret ? "ok" : "fail");
    };
    // ## 执行监听 ##
    $inner_text_worker->listen();
};

// 针对房间ID推送消息
$worker->uidConnections = array();
$worker->onMessage = function($connection, $data)
{
    global $worker;
    if(!isset($connection->roomId))
    {
        $connection->roomId = $data;
        $worker->uidConnections[$connection->roomId][] = $connection;
        return;
    }

};

// 当有客户端连接断开时
$worker->onClose = function($connection)
{
    global $worker;
    if(isset($connection->roomId))
    {
        // 连接断开时删除映射
        unset($worker->uidConnections[$connection->roomId]);
    }
};

// 华容道
function sendHrdUser($roomId, $message, $state)
{
    global $config,$worker;
    
    if(isset($worker->uidConnections[$roomId])){
        foreach($worker->uidConnections[$roomId] as $connection)
        {
            $connection->send($message);
        }
        
        try{
            // 建立MySQL链接
            $db = new Workerman\Lib\Db($config['db_host'], $config['db_port'], $config['db_user'], $config['db_pwd'], $config['db_name'], $config['pconnect']); 
              
            // 房主放弃 
            if($state == 3){ 
                $sql = "UPDATE `c_fight_info` SET `state` = 4 WHERE id = '$roomId'";
                $db->query($sql);
            }
            
            // 好友放弃
            if($state == 5){ 
                $sql = "UPDATE `c_fight_info` SET `state` = 1 WHERE id = '$roomId'";
                $db->query($sql);
            }
            
            // 准备开战
            if($state == 2){
                // 延迟器执行一次
                $time = isset($data['plus']) ? intval($data['plus']) : 0;
                if($time) {   
                    Timer::add($time, function() use($roomId, $db){
                        
                        // 设置游戏超时 2游戏中 => 5超时
                        $sql = "UPDATE `c_fight_info` SET `state` = 5 WHERE id = '$roomId' AND `state` = 2";
                        $db->query($sql);
                        
                        // 通知客户端
                        $contents['roomId'] = $roomId;
                        $contents['state'] = 8;
                        $contents['msg'] = '房间超时';
                        $client = stream_socket_client('tcp://127.0.0.1:5678', $errno, $errmsg, 1);
                        fwrite($client, json_encode($contents)."\n");
        
                    },'',false);
                }   
        
            }
        
        }catch(Exception $e){
            var_dump($e);
        }
        
        return true;
    }
}

// 永不言弃
function sendNgUser($roomId,$message)
{
    global $worker;
    if(isset($worker->uidConnections[$roomId])){
        foreach($worker->uidConnections[$roomId] as $connection)
        {
            $connection->send($message);
        }
        
        return true;
    }
}

// 枪王之王
function sendQwUser($roomId,$message)
{
    global $worker;
    if(isset($worker->uidConnections[$roomId])){
        foreach($worker->uidConnections[$roomId] as $connection)
        {
            $connection->send($message);
        }
        
        return true;
    }
}

// 搬砖大富翁
function sendMonolyUser($roomId,$invite_uid) {
   global $worker;
    if(isset($worker->uidConnections[$roomId])){

        if(!empty($invite_uid)) {
            $db = new Workerman\Lib\Db('127.0.0.1','3306','root','zzgame@)!*2018','monopoly_game');
            $sql = " SELECT id,nickname,avatar FROM `c_users` WHERE id = {$invite_uid}";  // 查询被邀请的用户的信息
            $ret = $db->query($sql);
        }
        $status = $ret ? $ret[0] : array();
        foreach($worker->uidConnections[$roomId] as $connection)
        {
            $connection->send(json_encode($status));
        }
      
        return true;
    } 
}

// 运行所有的worker
Worker::runAll();
